package audit;

import java.io.BufferedWriter;
import java.io.File;
import java.io.FileWriter;
import java.io.IOException;

import main.Main;

import fileProcessing.ParsingException;
import fileProcessing.ProjectDirectories;

public class AuditWriter {
	
	private FileWriter  auditFile;
	private long startTime = System.currentTimeMillis();
	private long prevTime;
	
	private AuditWriter() throws ParsingException{
	}
	
	public static AuditWriter getAuditWriter() throws ParsingException{
		return new AuditWriter();
	}
	
	public void setPrevTime(){
		prevTime = System.currentTimeMillis();
	}
	
	public void writeToAudit(String text) throws ParsingException{
		try {
			auditFile = new FileWriter(new File(ProjectDirectories.auditFileDir+"\\AuditLog.txt"), true);
			auditFile.write(text+"\r\n");
			auditFile.close();
		} catch (IOException e) {
			throw new ParsingException("Error writing the following message to the audit log: "+text);
		}
	}
	
	public void writeExecutionTime(String event) throws ParsingException{
		long time = System.currentTimeMillis();
		double timeInSeconds,timeInMinutes;
		
		if(event.equalsIgnoreCase("Final execution time: ")){
			timeInSeconds = (time-startTime)/1000.00;
			timeInMinutes = (time-startTime)/(1000.00*60.00);
		}
		else{
			timeInSeconds = (time-prevTime)/1000.00;
			timeInMinutes = (time-prevTime)/(1000.00*60.00);
		}
		
		String displayTime = (timeInSeconds+" seconds ("+timeInMinutes+" minutes)");
		Main.audit.writeToAudit(event+" "+displayTime+"\r\n");
		prevTime = time; 
	}
	
	public void closeAuditFile() throws ParsingException{
		try {
			auditFile.close();
		} catch (IOException e) {
			throw new ParsingException("Error closing audit file.");
		}
	}

}
